﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Modeling.Common.Utility;
using Microsoft.XLANGs.BaseTypes;
using System.Globalization;
using System.IO;
using System.Xml;

namespace BizTalk.ESB.Extensions.Helpers
{
    public class BamDefinitionPropertyManager
    {
        public BamDefinitionPropertyManager()
        {}

        private BusinessDataTracking manifest;
        private const string bamActivityCheckpointXpath = @"/*[local-name()='BAMDefinition']/*[local-name()='Activity']/*[local-name()='Checkpoint']";
        private const string bamActivityNameXpath = @"/*[local-name()='BAMDefinition']/*[local-name()='Activity']/@*[local-name()='Name']";

        public BamDefinitionPropertyManager(BusinessDataTracking manifest)
        {
            Guard.ArgumentNotNull(manifest, "manifest");
            this.manifest = manifest;
        }

        public static BamDefinitionPropertyManager Create(string BamDefinitionXmlFilePath)
        {
            Guard.ArgumentNotNullOrEmpty(BamDefinitionXmlFilePath, "BamActivityDefinitionFile");
            string path = BamDefinitionXmlFilePath;
            if (!Path.IsPathRooted(path))
            {
                path = RuntimeHelper.GetExecutionPath(path);
            }
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, "BAM Activity Definition File not found: {0}", new object[] { path }));
            }

            return new BamDefinitionPropertyManager(BuildBamManifestFromFile(path));
        }

        private static BusinessDataTracking BuildBamManifestFromFile(string BamDefinitionXmlFile)
        {
            var bamTrackingManifest = new BusinessDataTracking();
            var bamXmlFile = new XmlDocument();
            bamXmlFile.Load(BamDefinitionXmlFile);

            bamTrackingManifest.BamActivityName = bamXmlFile.SelectSingleNode(bamActivityNameXpath).Value;
            var BamDataFields = bamXmlFile.SelectNodes(bamActivityCheckpointXpath);
            foreach (XmlNode field in BamDataFields)
            {
                System.Diagnostics.Trace.WriteLine("BamDefinitionPropertyManager - Adding Field from BAM XML: " + field.Attributes["Name"].Value);
                bamTrackingManifest.AddDataTrackingPoint(field.Attributes["Name"].Value, null);
            }

            return bamTrackingManifest;
        }

        public BusinessDataTracking Manifest
        {
            get
            {
                return this.manifest;
            }
        }
    }
}
